import template from '../template';
import wx from 'weixin-js-sdk'

const orderStatus = new Map([
  ['0', '待付款'],
  ['1', '待发货'],
  ['2', '待收货'],
  ['3', '交易完成'],
])

class Order {
  constructor() {

  }

  static getList() {

  }

  static getOrder(orderId) {

  }


  // post order and pay
  static postOrder({num, points, goodsId, consigneeId, msg}) {
    return template({
      url: 'order/add',
      method: 'post',
      data: {
        type: 21,
        num,
        point: points,
        goods_id: goodsId,
        consignee_id: consigneeId,
        remark: msg
      },
      success: res => res.data.order_id
    });
  }

  static async payForOrder(orderId, cb) {
    const res = await Order.getPaymentArgs(orderId);

    typeof res === 'object' && Object.keys(res).forEach(k => {
      try {
        res[k] = String(res[k]);
      } catch (e) {
        console.log(e);
      }
    });

    const onBridgeReady = () => {
      WeixinJSBridge.invoke(
        'getBrandWCPayRequest', {
          appId: res.appId, //公众号名称，由商户传入
          timeStamp: res.timeStamp + '',         //时间戳，自1970年以来的秒数
          nonceStr: res.nonceStr, //随机串
          package: res.package,
          signType: res.signType, //微信签名方式：

          paySign: res.paySign //微信签名
        },


        function(res1) {
          console.log('xmy build::::::::', res1);
          if(res1.err_msg == "get_brand_wcpay_request:ok" ) {
            cb && cb(res1);
          } else if(res1.err_msg == "get_brand_wcpay_request:fail" ) {
            alert(JSON.stringify(res1))
          } else if(res1.err_msg == "get_brand_wcpay_request:cancel" ) {
            console.log('用户取消支付');
          }
        }

      );
    }


    if (typeof WeixinJSBridge == "undefined"){
       if( document.addEventListener ){
         document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
       }else if (document.attachEvent){
         document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
         document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
       }
    }else{
       onBridgeReady();
    }


    // wx.chooseWXPay({
    //   timestamp: res.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
    //   nonceStr: res.nonceStr, // 支付签名随机串，不长于 32 位
    //   package: res.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
    //   signType: res.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
    //   paySign: res.paySign, // 支付签名
    //   success: function (res) {
    //     // 支付成功后的回调函数
    //     cb && cb(res);
    //   }
    // })
  }

  static async getPaymentArgs(orderId) {
    return template({
      url: `member/order/pay/${orderId}`,
      method: 'post'
    });
  }

  static async purchase({num, points, goodsId, consigneeId, msg, cb}) {
    const orderId = await Order.postOrder({num, points, goodsId, consigneeId, msg});
    Order.payForOrder(orderId, cb);
  }

  // 订单列表
  // status 0 未支付；1 已支付； 2 已发货； 3 完成； 不传 全部订单
  static getOrdersList(status) {
    return template({
      url: 'goods_order/order_list',
      // data: {status}
    });
  }

  // 订单详情
  static getOrderDetail(orderId) {
    return template({
      url: 'goods_order/order?id=' + orderId
    });
  }

  // 完成订单
  static confirmOrder(orderId) {

  }

  static orderAdaptor(raw) {
    return {
      oid: raw.id,
      status: (Number(raw.status) + 1) % 4,
      orderNum: raw.order_no,
      trackNum: raw.logistics_code,
      count: raw.num,
      proName: raw.goods.name,
      imgSrc: raw.goods.images.split(',')[0],
      price: raw.goods.price,
      totalPrice: parseFloat(raw.goods.price * raw.num).toFixed(2),
      itemName: orderStatus.get(String(raw.status)),
      statusCn: orderStatus.get(String(raw.status)),
      orderTime: raw.created_at,
      payTime: raw.pay_at || '',
      raw
    };
  }

}

export default Order;
